
<template>
	<div class="watersStationInput" v-loading="watersStationLoading">
		<div class="stationInfo">
      <div class="title">站点信息</div>
      <el-form :model="inputForm" :rules="inputFormRules" style="width: 65%" size="mini" ref="inputForm" label-width="110px">
        <!-- <el-form-item label="活动区域" prop="station">
          <el-select v-model="ruleForm.station" placeholder="请选择水站名称">
            <el-option label="区域一" value="shanghai"></el-option>
            <el-option label="区域二" value="beijing"></el-option>
          </el-select>
        </el-form-item> -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="水站名称" prop="stationName" >
              <el-input v-model="inputForm.stationName" placeholder="请填写水站名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="站点编号" prop="stationNumbering" >
              <el-input v-model="inputForm.stationNumbering" placeholder="请填写站点编号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="站点地址" prop="stationAddress" >
              <el-input v-model="inputForm.stationAddress" placeholder="请填写站点地址" @focus="openMapDialog"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经纬度">
              <el-col :span="11">
                <el-input v-model="inputForm.longitude" placeholder="经度" disabled></el-input>
              </el-col>
              <el-col :span="2" style="text-align: center;"> , </el-col>
              <el-col :span="11">
                <el-input v-model="inputForm.latitude" placeholder="纬度" disabled></el-input>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="监测因子" prop="pollutionFactor" >
            <el-select
              style="width: 100%"
              v-model="inputForm.pollutionFactor"
              multiple
              placeholder="请选择监测因子">
              <el-option
                v-for="item in factorsOption"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="管理人员" prop="stationId" >
              <!-- <el-input v-model="inputForm.person" placeholder="请填写管理人员"></el-input> -->
              <el-select v-model="inputForm.stationId" placeholder="请填写管理人员" @change="personChange">
                <p v-for="(item, index) of stationUsers" :key="index">
                  <el-option :label="item.username" :value="item.id"></el-option>
                </p>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone" >
              <el-input v-model="inputForm.phone" placeholder="请填写联系电话" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="身份证号码" prop="identity" style="width: 100%">
          <el-input v-model="inputForm.identity" placeholder="请填写身份证号码" disabled></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="运维人员" prop="operationId" >
              <!-- <el-input v-model="inputForm.person" placeholder="请填写管理人员"></el-input> -->
              <el-select v-model="inputForm.operationId" placeholder="请选择运维人员">
                <p v-for="(item, index) of stationOperation" :key="index">
                  <el-option :label="item.username" :value="item.id"></el-option>
                </p>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="监测系统编号" prop="monitorSystem">
              <!-- <el-input v-model="inputForm.person" placeholder="请填写管理人员"></el-input> -->
              <el-select v-model="inputForm.monitorSystem" placeholder="请选择监测系统编号" :loading="monitorSystemLoading" @focus="monitorSystemFocus">
                <p v-for="(item, index) of monitorSystemList" :key="index">
                  <el-option :label="item" :value="item"></el-option>
                </p>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-form-item label="上传图片" label-width="100px" style="margin-top: 15px;">
          <el-upload
            ref="uploadPhoto"
            action=""
            :file-list="inputForm.files"
            list-type="picture"
            multiple
            :limit="2"
            :on-change="uploadChange"
            :on-exceed="uploadExceed" 
            :http-request="handleSubmit"
            :auto-upload="false"
          >
            <el-button>点击上传</el-button>
            <span slot="tip" class="uploadTip">请上传身份证正反面</span>
          </el-upload>
        </el-form-item> -->
      </el-form>
    </div>
		<div class="enterprises">
      <div class="title">相关排污企业
        <span class="formAddBtn">
          <el-button class="greenBtn" size="mini" @click="addInput(['pollutantNumbering', 'pollutantName'])">新增一项</el-button>
          <el-button size="mini" @click="delInput">删除</el-button>
        </span>
      </div>
      <el-form style="width: 65%" size="mini" label-width="80px">

        <el-row v-for="(item, index) of enterprisesForm" :key="index">
          <el-col :span="12">
            <el-form-item :label="'编号' + (index > 0 ? index : '')" style="margin-right:8px;">
              <el-input v-model="item.pollutantNumbering" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="'企业名称' + (index > 0 ? index : '')">
              <!-- <el-input v-model="item.pollutantName"></el-input> -->
              <el-select v-model="item.pollutantName" placeholder="请选择企业名称" @change="((val) => {pollutantChange(val, index)})">
                <p v-for="(citem, cindex) of stationPollutant" :key="cindex">
                  <el-option :label="citem.pollutantName" :value="citem.pollutantName"></el-option>
                </p>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
    </div>
    <div class="submitBtn">
      <el-button class="greenBtn" size="mini" @click="submit('inputForm')">提交</el-button>
    </div>

    <el-dialog title="选择站点地址" width="80%" class="mapDialog" :visible.sync="mapDialogFlag" @close="destroyMap" append-to-body>
      <div class="mapInfoCnt">
        <el-form :inline="true" :model="inputForm" size="mini">
          <el-row>
            <el-col :span="9">
              <el-form-item label="" style="width: 100%;" class="selectAddr">
                <el-input v-model="inputForm.stationAddress" style="width: 98%;">
                  <template slot="prepend">地址</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item label="">
                <el-button round type="primary" @click="geoCode">地址 => 经纬度</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="">
                <el-input placeholder="请输入经度" v-model="inputForm.longitude">
                  <template slot="prepend">经度</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="">
                <el-input placeholder="请输入纬度" v-model="inputForm.latitude">
                  <template slot="prepend">纬度</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          
          
          
          
        </el-form>
      </div>
      <div id="map" class="map" v-loading="mapIsLoading" element-loading-background="rgba(249, 249, 249, 0.8)"></div>
    </el-dialog>
	</div>
</template>
<script>
import MapLoader from "../plugins/AMap.js";
import { mapActions, mapGetters} from "vuex"
let marker, geocoder; //地图点标记 和 地图地理编码 
export default {
  name: 'watersStationInput',
  data () {
    return {
      msg: 'hello watersStationInput!',
      watersStationLoading: false,
      mapDialogFlag: false,
      // formData: {},
      map: null,
      mapIsLoading: false,
      monitorSystemLoading: false,
      inputForm: {
        stationName: '',
        stationNumbering: '',
        pollutionFactor: '',

        stationAddress: '',
        longitude: '',
        latitude: '',

        stationId: '',
        phone: '',
        identity: '',

        operationId: '',
        monitorSystem: '',
      },
      inputFormRules: {
        stationName: [
          { required: true, message: '请填写水站名称', trigger: 'blur' },
        ],
        stationNumbering: [
          { required: true, message: '请填写站点编号', trigger: 'change' }
        ],
        stationAddress: [
          { required: true, message: '请填写站点地址', trigger: 'change' }
        ],
        pollutionFactor: [
          { required: true, message: '请选择监测因子', trigger: 'blur' }
        ],
        stationId: [
          { required: true, message: '请选择管理人员', trigger: 'change' }
        ],
        operationId: [
          { required: true, message: '请选择运维人员', trigger: 'change' }
        ],
        monitorSystem: [
          { required: true, message: '请选择监测系统编号', trigger: 'change' }
        ],
        
      },
      enterprisesForm: [
        {
          pollutantNumbering: '',
          pollutantName: ''
        },
      ],
      monitorSystemList: []
		}
  },
	methods: {
    ...mapActions([
      'fetchWaterStationUsers',
      'fetchWaterOperationuser',
      'fetchWaterStationPollutant',
      'postWaterStationAdded',
      'fetchMonitorSystemSel'
    ]),
    addInput(newInput) {
      let group = this.enterprisesForm
      let newitem = {}
      newInput.map((item) => {
        newitem[item] = ''
      })
      group.push(newitem)
    },
    delInput() {
      let group = this.enterprisesForm
      if(group.length > 1) {
        group.splice(-1)
      }
    },
    submit(formName) {
      // let that = this
      let inputForm = this.inputForm
      this.$refs[formName].validate(async (valid) => {
        if(valid) {
          this.watersStationLoading = true

          let params = {
            stationName: inputForm.stationName,
            stationNumbering: inputForm.stationNumbering,
            stationAddress: inputForm.stationAddress,
            pollutionFactor: inputForm.pollutionFactor.join(),
            longitude: inputForm.longitude,
            latitude: inputForm.latitude,
            stationId: inputForm.stationId,
            operationId: inputForm.operationId,
            monitorSystem: inputForm.monitorSystem,
            pollutions: [...this.enterprisesForm]
          }
          let result = await this.postWaterStationAdded(params)
          if(result.message != 'success') {
            this.$notify.warning({
              title: '警告',
              message: result.info,
            })
            this.watersStationLoading = false
            return
          }
          this.$notify.success({
            title: '成功',
            message: '新增站点成功',
          })
          this.$router.push('/waters/stationList')
        }else {
          return false;
        }
      })
    },
    personChange(val) {
      let userInfo = this.stationUsers.find(v => v.id === val)
      this.inputForm.phone = userInfo.phone
      this.inputForm.identity = userInfo.identity
    },
    pollutantChange(val, index) {
      let pollutant = this.stationPollutant.find(v => v.pollutantName === val)
      this.enterprisesForm[index].pollutantNumbering = pollutant.pollutantNumbering
    },
    openMapDialog() {
      this.mapIsLoading = true
      this.createMap()
      this.mapDialogFlag = true
    },
    destroyMap() {
      this.map && this.map.destroy()
      // marker = null 
    },
    createMap() {
      let that = this
      MapLoader().then(
        AMap => {
          that.map = new AMap.Map('map', {
            center: [113.850234,22.673635],
            mapStyle: 'amap://styles/b23dc72b03be03f4dd932c413bc85c94',
            zoom: 11,
            zooms: [11, 18],
            resizeEnable: true
          })
          AMap.plugin(['AMap.ToolBar','AMap.Geocoder'],function(){//异步加载插件
            that.map.addControl(new AMap.Geocoder());
            that.map.addControl(new AMap.ToolBar());
          })
          that.map.on('click',(e) => {
            that.inputForm.longitude = e.lnglat.lng
            that.inputForm.latitude = e.lnglat.lat
            that.regeoCode()
          })
          if(marker) {
            that.map.add(marker)
            that.map.setFitView(marker)
          }
          that.mapIsLoading = false
        },
        e => {
        }
      );
      
    },
    regeoCode() {
      let that = this
      let map = that.map
      let longitude = that.inputForm.longitude
      let latitude = that.inputForm.latitude
      if(!geocoder){
        geocoder = new AMap.Geocoder({
          radius: 1000
        });
      }
      if(!marker){
        marker = new AMap.Marker();
        map.add(marker);
      }
      marker.setPosition(new AMap.LngLat(longitude, latitude));
      geocoder.getAddress(longitude + ',' + latitude, (status, result) => {
        if (status === 'complete' && result.regeocode) {
          let address = result.regeocode.formattedAddress
          that.inputForm.stationAddress = address
        }else{
          this.$message.error('根据经纬度查询地址失败')
        }
      })
    },
    geoCode() {
      let that = this
      let map = that.map
      let stationAddress = that.inputForm.stationAddress
      if(!geocoder){
        geocoder = new AMap.Geocoder({
          radius: 1000
        })
      }
      geocoder.getLocation(stationAddress,(status, result) => {
        if (status === 'complete' && result.geocodes.length) {
          var lnglat = result.geocodes[0].location
          that.inputForm.longitude = lnglat.lng
          that.inputForm.latitude = lnglat.lat
          if(!marker){
            marker = new AMap.Marker();
            map.add(marker);
          }
          marker.setPosition(lnglat);
          map.setFitView(marker);
        }else{
          this.$message.error('根据地址查询位置失败')
        }
      });
    },
    async monitorSystemFocus() {
      this.monitorSystemLoading = true
      this.monitorSystemList = await this.fetchMonitorSystemSel()
      this.monitorSystemLoading = false
    }
  },
  async created() {
    this.watersStationLoading = true
    await this.fetchWaterStationUsers()
    await this.fetchWaterOperationuser()
    await this.fetchWaterStationPollutant()
    this.watersStationLoading = false
  },
  destroyed() {
    marker = geocoder = null
  },
  computed: {
    ...mapGetters({
      stationUsers: 'getStationUsers',
      stationOperation: 'getStationOperation',
      stationPollutant: 'getStationPollutant',
      factorsOption: 'getFactorsOption',
    })
  },
}
</script>
<style scoped>
.watersStationInput .title {
  position: relative;
  left: 20px;
  line-height: 70px;
  font-size: 16px;
}
.watersStationInput .title::before {
  content: '';
  position: absolute;
  left: -15px;
  width: 4px;
  height: 20px;
  top: 25px;
  background-color: #2399ff;
}
.stationInfo,
.enterprises {
  background: #fff;
  padding: 0 20px 35px 20px;
  margin-bottom: 15px;
}
.watersStationInput .uploadTip {
  margin-left: 15px;
  font-size: 12px;
}
.submitBtn {
  background: #fff;
  padding: 20px;
  margin-top: -15px;
}
.mapDialog .map {
  width: 100%;
  height: 500px;
}
.mapDialog .mapInfoCnt {
  padding: 15px 15px 0 15px;
  background: #fff;
}
</style>
<style>
.selectAddr .el-form-item__content {
  width: 100%;
}
</style>